package controller;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-01-17
 * Time: 下午 21:28
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //告诉HttpServlet以utf8的格式来解析请求
        req.setCharacterEncoding("utf8");

        //判断用户名和密码是否为空
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if(username == null || password == null || username.equals("") || password.equals("")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("您输入的账号或密码为空!");
            return;
        }


        //判读账号密码是否正确
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);

        if(user == null) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("您输入的账号密码错误!");
            return;
        }

        if(!user.getPassWord().equals(password)) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("您输入的账号密码错误!");
            return;
        }

        //登录成功
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取登录状态
        HttpSession session = req.getSession(false);
        //如果没有会话,代表未登录则返回
        if(session == null) {
            resp.setStatus(403);
            return;
        }

        //如果登录了,但是没有用户信息也表示未登录返回
        User user = (User)session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            return;
        }

        //如果会话有,账户信息也有那就表示以登录!
        resp.setStatus(200);

    }
}
